import React, { useEffect, useState } from 'react'
import { Select, SelectProps } from 'antd'
import { DefaultOptionType } from 'antd/lib/cascader'

const DynamicOptionsSelect: React.FC<SelectProps> = ({ options, ...attrs }) => {
  const [dynamicOptions, setDynamicOptions] = useState<DefaultOptionType[]>([])
  useEffect(() => {
    setDynamicOptions(options)
  }, [options])
  const handleSearch = (newValue: string) => {
    if (!newValue || options?.find(option => option.label === newValue)) return setDynamicOptions(options)
    setDynamicOptions([...options, { label: newValue, value: newValue }])
  }
  return (
    <Select
      showSearch
      allowClear
      onSearch={handleSearch}
      options={dynamicOptions}
      {...attrs}
    ></Select>
  )
}
export default DynamicOptionsSelect
